<template>
  <div>
    <div>
      <el-tree
        ref="tree"
        :data="treeList"
        :props="{ 'label' : 'name' }"
        node-key="id"
        show-checkbox
        default-expand-all
        check-strictly
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>

  </div>
</template>

<script>
// 权限列表
import { getPermissionListAPI } from '@/api/permission'
// 树形数据
import { tranListToTreeData } from '@/utils/index'
// 接口api
import { getThisRoleAPI, assignPermAPI } from '@/api/setting'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [String, Number],
      required: true // 必传
    }
  },
  data() {
    return {
      treeList: [] // 树形数据
    }
  },
  created() {
    // 调用获取权限列表的方法
    this.getPermissionList()
    // 调用获取当前角色权限的方法
    this.getThisRole()
  },
  methods: {
    // 确认添加权限
    async setRolesBtn() {
      // this.$refs.tree.getCheckedKeys() 获取当前选择权限
      const permIds = this.$refs.tree.getCheckedKeys()
      // console.log(permIds)
      const res = await assignPermAPI({
        id: this.roleId, // id
        permIds: permIds // 权限
      })
      // console.log(res)
      this.$message.success(res.message)

      // 关闭弹框
      this.$emit('close')
      // 重新获取权限列表
      this.getPermissionList()
    },

    // 获取当前角色权限
    async getThisRole() {
      const res = await getThisRoleAPI(this.roleId)
      // console.log(res)
      // 得到当前角色信息权限
      // this.thisQuanXian = res.data.permIds
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },

    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionListAPI()
      // console.log(res)
      // 将获取到的数据处理成树形数据,赋值给 treeList
      this.treeList = tranListToTreeData(res.data, '0')
    },

    // 取消添加权限
    cancelButton() {
      this.$emit('close')
    }
  }
}
</script>

<style>

</style>
